<script>
import {defineComponent} from 'vue'

export default defineComponent({
  name: "Emp",
  data:function () {
    return{
      aryEmp:[],
      currentPage: 1,//当前页
      // currentIndex: '',//当前索引
      pagesize: 5,
      queryForm:{
        deptNo:'',
        empName:''
      },
      aryDept:[],
      visibleAddEmp:false,
      addForm:{
        empNo:'',
        empName:'',
        job:'',
        dept:{
          deptNo: ''
        }
      },
      rules: {
        empNo: [
          {required: true, message: '员工账号不能为空', trigger: 'blur'},
          {min: 3, max: 10, message: '账号必须在3-10为之间', trigger: 'blur'}
        ],
        empName: [
          {required: true, message: '员工名称不能为空', trigger: 'blur'}
        ],
        job: [
          {required: true, message: '员工职务不能为空', trigger: 'blur'}
        ]
      },
      visibleUpdateEmp:false,
      updateForm:{
        empNo:'',
        empName:'',
        job:'',
        dept:{
          deptNo: ''
        }
      }
    }
  },
  methods:{
    initEmp:function () {
      this.axios.get("http://localhost:8088/emp/find").then(response=>{
        this.aryEmp=response.data;
      })
    },
    handleSizeChange(val) {
      this.pagesize = val;
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.currentPage= val
    },
    initDept:function () {//绑定部门下拉列表
      this.axios.get("http://localhost:8088/dept/find").then(response=>{
        this.aryDept=response.data;
      })

    },
    queryDept:function () {

      this.axios.get("http://localhost:8088/emp/findBC?deptNo="+this.queryForm.deptNo+"&empName="+this.queryForm.empName)
        .then(response=>{
          this.aryEmp=response.data;
        })
    },
    addEmp:function () {
      this.visibleAddEmp=true;

    },
    cancelEmp:function (){
      this.visibleAddEmp=false;
      this.addForm=this.$options.data().addForm;
    },
    cancelupdateEmp:function () {
      this.visibleUpdateEmp=false;
      this.updateForm=this.$options.data().updateForm;
    },
    saveEmp:function () {
      //获取要验证的表单，进行验证
      this.$refs.addForm.validate((valid)=>{
        if (valid){
          this.axios.post("http://localhost:8088/emp/add",this.addForm).then(response=>{
            if (response.data="success"){
              this.$message({
                showClose: true,
                message: '添加员工成功',
                type: 'success'
              })
            }else {
              this.$message({
                showClose: true,
                message: '添加员工失败',
                type: 'error'
              })
            }
            //关闭模态窗
            this.visibleAddEmp=false;
            //初始化表单
            this.addForm=this.$options.data().addForm;
            //数据更新
            //从新调用所有员工数据
            this.initEmp();
          })
        }
      });
    },
    showUpdateForm:function (data) {
      this.visibleUpdateEmp=true;
      this.updateForm.empNo=data.empNo;
      this.updateForm.empName=data.empName;
      this.updateForm.job=data.job;
      this.updateForm.dept.deptNo=data.dept.deptNo;
    },
    saveUpdateEmp:function () {
      //获取要验证的表单，进行验证
          this.axios.post("http://localhost:8088/emp/update",this.updateForm).then(response=> {
            if (response.data = "success") {
              this.$message({
                showClose: true,
                message: '修改成功',
                type: 'success'
              })
              this.visibleUpdateEmp=false;
              this.updateForm=this.$options.data().updateForm;
              this.initEmp();
            } else {
              this.$message({
                showClose: true,
                message: '修改失败',
                type: 'error'
              })
            }
          })
        },
    deleteEmp:function (empNo) {
      this.$confirm("确认删除此员工吗？","确认删除",{
        confirmButtonText:"确定",
        cancelButtonClass:"取消",
        type:'warning'
      }).then(
        ()=>{
          this.axios.get("http://localhost:8088/emp/delete?empNo="+empNo).then(response=>{
            if (response.data="success"){
              this.$message({
                type:"success",
                message:"删除成功 ！"
              });
              this.initEmp();
            }else {
              this.$message({
                type:"error",
                message:"删除失败 ！"
              })
            }
          })

        }
      )
    },
    exportToExcel:function () {
      window.location.href="http://localhost:8088/dept/export";
    },
    handleError:function (err) {
      //是el-upload自动调用的钩子函数：在上传失败后，回调
      this.$message({
        type:"info",
        message:"上传失败！"
      })
    },
    handleBeforeUpload:function (file) {
      //当在打开窗口，选择而完文件后，上传之前所调用的钩子函数
      //通常拥有验证上传的文件的格式
      alert("aaa")
      //1、在数组里存储允许上传的文件的格式
      let ary=['xlsx', 'xls'];
      //2、通过形参来获取要上传的文件的扩展名
      let name=file.name;
      alert("name")
      let extendsName=name.substring(name.lastIndexOf(".")+1);
      //alert(extendsName);
      if(!ary.includes(extendsName)){
        this.$message({
          type:"info",
          message:"文件格式不正确！"
        });
        return false;
      }

    },
    handleSuccess:function () {
      this.$message({
        type:"success",
        message:"文件导入成功"
      })
    },
    uploadFile:function (file) {
      //选完文件，点打开后调用的函数
      //1、创建FormData对象：用于存储要上传的文件
      let formData=new FormData();
      //2、通过形参获取到要导入的文件
      let excel=file.raw;
      //3、把获取到的文件存储到formData对象中
      formData.append("file",excel);
      //4、请求后端接口
      //文件上传：post
      this.axios({
        url:"http://localhost:8088/dept/upLoad",
        method:"post",
        data:formData,
        headers:{
          'Content-Type': 'multipart/form-data'
        }
      }).then(response=>{
        this.$message({
          type:"info",
          message:response.data
        })
      })
    }
  },
  mounted() {
    this.initEmp();
      this.initDept();
  }
})
</script>

<template>
<div>
  <h1>员工信息维护</h1>
  <el-form :inline="true" :model="queryForm" class="demo-form-inline">
    <el-form-item label="所在部门">
      <el-select v-model="queryForm.deptNo" placeholder="请选择所在部门">

        <el-option v-for="dept in aryDept" :label="dept.deptName" :value="dept.deptNo"></el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="员工姓名">
      <el-input v-model="queryForm.empName" placeholder="输入员工姓名"></el-input>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="queryDept()">查询</el-button>
      <el-button type="primary" @click="addEmp()">添加员工</el-button>
      <el-button type="primary" @click="exportToExcel()">导出为Excel</el-button>
      <el-upload style="display: inline-block;"
                 ref="upload"
                 class="upload-demo"
                 action="#"
                 accept=".xlsx, .xls"
                 :auto-upload="false"
                 :on-change="uploadFile"
                 :show-file-list="false"
                 :before-upload="handleBeforeUpload"
                 :on-error="handleError"
                 :on-success="handleSuccess"

      >
        <el-button type="primary">导入Excel</el-button>
      </el-upload>
    </el-form-item>
  </el-form>

  <el-table :data="aryEmp.slice((currentPage-1)*pagesize,currentPage*pagesize)"
            border style="width: 100%; margin-top: 20px"
            :header-cell-style="{
                background: 'powderblue',
                color:'black',
                textAlign:'center',
                padding:'5px 0'
              }"
  >
    <el-table-column label="员工编号" prop="empNo" width="100px"/>
    <el-table-column label="员工姓名" prop="empName" width="100px"/>
    <el-table-column label="员工职务" prop="job" width="150px"/>
    <el-table-column label="部门编号" prop="dept.deptNo" width="60px"/>
    <el-table-column label="部门名称" prop="dept.deptName" width="100px"/>
    <el-table-column label="部门位置" prop="dept.loc" />
    <el-table-column label="操作" >
      <template slot-scope="scope">
        <el-button @click="showUpdateForm(scope.row)"><i class="el-icon-edit"></i></el-button>
        <el-button type="primary" icon="el-icon-search"></el-button>
        <el-button @click="deleteEmp(scope.row.empNo)"><i class="el-icon-delete"></i></el-button>
      </template>
    </el-table-column>

  </el-table>
  <!--修改窗口-->
  <el-dialog title="修改员工信息"    :visible.sync="visibleUpdateEmp" width="50%" center>
    <el-form  :model="updateForm" ref="updateForm" :rules="rules" label-width="80px">
      <el-form-item label="员工编号" prop="empNo">
        <el-input v-model="updateForm.empNo"></el-input>
      </el-form-item>
      <el-form-item label="员工名称" prop="empName">
        <el-input v-model="updateForm.empName"></el-input>
      </el-form-item>
      <el-form-item label="员工职务" prop="job">
        <el-input v-model="updateForm.job"></el-input>
      </el-form-item>
      <el-form-item label="所属部门">
        <el-select v-model="updateForm.dept.deptNo" placeholder="请选择部门">
          <el-option v-for="dept in aryDept" :label="dept.deptName"
                     :value="dept.deptNo"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="saveUpdateEmp()">修改</el-button>
      <el-button  @click="cancelupdateEmp()">取 消</el-button>
    </span>
  </el-dialog>
  <!--/修改窗口-->
  <!--  添加员工模态窗-->
  <el-dialog title="添加员工" :visible.sync="visibleAddEmp" width="50%" center>
    <el-form :model="addForm" ref="addForm" :rules="rules" label-width="80px">
      <el-form-item label="员工编号" prop="empNo">
        <el-input v-model="addForm.empNo"></el-input>
      </el-form-item>
      <el-form-item label="员工名称" prop="empName">
        <el-input v-model="addForm.empName"></el-input>
      </el-form-item>
      <el-form-item label="员工职务" prop="job">
        <el-input v-model="addForm.job" ></el-input>
      </el-form-item>
      <el-form-item label="所属部门">
        <el-select v-model="addForm.dept.deptNo" placeholder="请选择部门">
          <el-option v-for="dept in aryDept" :label="dept.deptName" :value="dept.deptNo" ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
<el-button type="primary" @click="saveEmp()">保 存</el-button>
<el-button @click="cancelEmp()">取 消</el-button>
    </span>
  </el-dialog>
  <!--  /添加员工模态窗-->
  <el-pagination
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    :current-page="currentPage"
    :page-sizes="[2,3,4,6,8,10,12,14,16,18]"
    :page-size=pagesize
    layout="total, sizes, prev, pager, next, jumper"
    :total="aryEmp.length">
  </el-pagination>
</div>

</template>

<style scoped>

</style>
